package com.ikangtai.shecare.personal;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.CollectedArticle;
import com.ikangtai.shecare.common.al.Algorithm;
import com.ikangtai.shecare.common.al.CycleUnitDS;
import com.ikangtai.shecare.common.al.DayUnitDSInput;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.al.UserUnitDS;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.LoginDownloadMsgInMyDeviceChoose;
import com.ikangtai.shecare.common.eventBusMsg.LoginInfoInMyDeviceChoose;
import com.ikangtai.shecare.common.httpBean.GetAllTask;
import com.ikangtai.shecare.common.util.ActivityCollector;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.DeviceInfo;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.SDCardHelper;
import com.ikangtai.shecare.main.MainActivity;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.record.bean.UserTemperatureInfo;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyDeviceChooseActivity extends BaseActivity implements View.OnClickListener {

    private LayoutInflater inflater;

    private TopBar topBar;
    private Button chooseShecare1, chooseShecare2;
    private String type;
    private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 106;
    private boolean requestPermissionFlag;

    private UMShareAPI mShareAPI = null;
    private int registerSimpleType = 0;
    private String openID = null;

    private ProgressDialog progressDialog;
    private DBManager dbManager;
    private LoginInfoInMyDeviceChoose loginInfo = new LoginInfoInMyDeviceChoose();
    private String buildType;
    private LoginDownloadMsgInMyDeviceChoose loginDownloadMsg = new LoginDownloadMsgInMyDeviceChoose();
    private boolean isOldUsersUpdated = false;
    private boolean needInitMemory = true;
    private int isNeedFirstExecAL;
    private Algorithm algorithm;

    private static final int LOGIN_OK = 1;
    private static final int LOGIN_NOK = 2;
    private static final int NO_USER = 3;
    private static final int PASSWORD_WRONG = 4;
    private static final int PASSWORD_WRONG_WITH_VALIDATE_CODE = 5;
    private static final int VALIDATE_CODE_NO = 6;
    private static final int VALIDATE_CODE_WRONG = 7;
    private static final int VALIDATE_CODE_OVERDUE = 8;
    private static final int FAIL_TO_GET_DB_VERSION = 9;

    private final int NO_DEVICEID_PARAM_FOUND = 0;
    private final int NO_DEVICEID_FOUND = 1;
    private final int SAME_DEVICEID_FOUND = 2;
    private final int DIFF_DEVICEID_FOUND = 3;

    private LinearLayout thirdLoginLayout;
    private TextView registerByOtherWayText;

    public void onClickAuth(View view) {
        SHARE_MEDIA platform = null;
        if (view.getId() == R.id.sina) {
            platform = SHARE_MEDIA.SINA;
        } else if (view.getId() == R.id.qq) {
            platform = SHARE_MEDIA.QQ;
        } else if (view.getId() == R.id.wechat) {
            platform = SHARE_MEDIA.WEIXIN;
        }
        /**begin invoke umeng api**/

        mShareAPI.doOauthVerify(this, platform, umAuthListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_device_choose);
        ActivityCollector.addActivity(this);
        mShareAPI = UMShareAPI.get(this); // 友盟第三方登录相关
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        inflater = LayoutInflater.from(MyDeviceChooseActivity.this);
        requestPermissionFlag = true;
        dbManager = new DBManager(this);
        buildType = getResources().getString(R.string.buildType);
        App.activityList.add(this);
        EventBus.getDefault().register(this);
        algorithm = new Algorithm(this);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (ContextCompat.checkSelfPermission(MyDeviceChooseActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if(requestPermissionFlag){
                ActivityCompat.requestPermissions(MyDeviceChooseActivity.this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
                requestPermissionFlag = false;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                Toast.makeText(MyDeviceChooseActivity.this, R.string.device_choose_toast, Toast.LENGTH_LONG).show();
            }
        }
    }


    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        chooseShecare1 = (Button) findViewById(R.id.chooseShecare1);
        chooseShecare1.setOnClickListener(this);
        chooseShecare2 = (Button) findViewById(R.id.chooseShecare2);
        chooseShecare2.setOnClickListener(this);
        thirdLoginLayout = (LinearLayout) findViewById(R.id.thirdLoginLayout);
        registerByOtherWayText = (TextView) findViewById(R.id.registerByOtherWayText);

        if(!(type == null || type.length() <= 0)){
            if(type.equals("bindThermometer")){
                thirdLoginLayout.setVisibility(View.GONE);
                registerByOtherWayText.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chooseShecare1:
                Intent version1Intent = new Intent(this, MyDeviceVersion1Activity.class);
                version1Intent.putExtra("type", type);
                startActivity(version1Intent);
                break;
            case R.id.chooseShecare2:
                Intent version2Intent = new Intent(this, MyDeviceVersion2Activity.class);
                version2Intent.putExtra("type", type);
                startActivity(version2Intent);
                break;
        }
    }

    /**
     * auth callback interface
     **/
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            AppLog.i("Authorize succeed, user info: " + data.toString());
            if (platform.toString().equals("WEIXIN")) {
                registerSimpleType = 1;
                openID = data.get("openid");
            } else if (platform.toString().equals("QQ")) {
                registerSimpleType = 3;
                openID = data.get("openid");
            } else if (platform.toString().equals("SINA")) {
                registerSimpleType = 2;
                openID = data.get("uid");
            }
            showProgressDialog();
            doLogin("", "",openID);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            AppLog.i("Authorize fail");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            AppLog.i("Authorize cancel");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

//        if (dbManager.getSqliteKeyValue(edt_user_name.getText().toString().trim(), "userName") == null)
//            progressDialog.setMessage(getString(R.string.firstLogining));
//        else
            progressDialog.setMessage(getString(R.string.logining));

        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    private void doLogin(final String userName, final String userPswd, final String openID) {

        // 如果是同一个用户登录，不需要重新initMemory
//        if (edt_user_name.getText().toString().trim().equals(App.userName))
//            needInitMemory = false;
//        else
//            needInitMemory = true;

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        loginInfo.setUserName(userName);
        loginInfo.setUserPswd(userPswd);

        String appendUrl;

        if (buildType.equals("god"))
            appendUrl = "login/internal.json";
        else
            appendUrl = "login/login.json";

        try {
            okHttpClient.add("emailOrPhone", userName);

            if (!buildType.equals("god")) {
                okHttpClient.add("password", userPswd);

                String phoneID = DeviceInfo.getDeviceID();
                okHttpClient.add("phoneID", phoneID);
                AppLog.i("phoneID = " + phoneID);
            }

            if(!(openID == null || openID.length()<=0)){
                okHttpClient.add("serviceID", openID);
            }

//            if (login_validate_code.getVisibility() == View.VISIBLE) {
//                okHttpClient.add("verifyCode", login_validate_code.getText().toString().trim());
//            }
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp();
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        AppLog.e("" + respCode);
                        if (200 == respCode) {

                            if(!(openID == null || openID.length()<=0)){
                                App.userName = respJSONObj.getString("emailOrPhoneNumber");
                            }else {
                                App.userName = userName;
                            }

                            App.userPswd = userPswd;
                            App.authToken = respJSONObj.getString("authToken");
                            loginInfo.setRespCode(LOGIN_OK);
                            if (!respJSONObj.isNull("isDeviceChanged")) {
                                loginInfo.setIsDeviceChanged(respJSONObj.getInt("isDeviceChanged"));
                            } else {
                                loginInfo.setIsDeviceChanged(1);
                            }
                            sendOKResp(loginInfo);
                            AppLog.i("login onResponse success! App.authToken = " + App.authToken);
                        } else if (216 == respCode) {
                            Intent intent = new Intent(MyDeviceChooseActivity.this, RegisterActivity.class);
                            intent.putExtra("registerSimpleType", registerSimpleType);
                            intent.putExtra("openID", openID);
                            startActivity(intent);
                            dismissProgressDialog();
                        } else {
                            sendNOKResp();
                            AppLog.i("login onResponse failed! respCode is:" + respCode);
                        }
                    } catch (JSONException e) {
                        sendNOKResp();
                        AppLog.i("login onResponse failed!");
                        e.printStackTrace();
                    }
                }

                private void sendNOKResp() {
                    LoginInfoInMyDeviceChoose loginInfo = new LoginInfoInMyDeviceChoose(LOGIN_NOK);
                    EventBus.getDefault().post(loginInfo);
                }

                private void sendOKResp(LoginInfoInMyDeviceChoose loginInfo) {
                    AppLog.i("begin EventBus post after login!");
                    EventBus.getDefault().post(loginInfo);
                    AppLog.i("begin EventBus post after login2!");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Subcriber
    private void handleLoginInMyDeviceChoose(LoginInfoInMyDeviceChoose loginInfo) {
        switch (loginInfo.getRespCode()) {
            case LOGIN_OK:
                downloadData(loginInfo.getIsDeviceChanged());
                break;
            case LOGIN_NOK:
                dismissProgressDialog();
                break;
            case FAIL_TO_GET_DB_VERSION:
                dismissProgressDialog();
                App.authToken = loginInfo.getAuthToken();
                break;
        }
    }

    private void downloadData(int deviceId) {
        switch (deviceId) {
            case NO_DEVICEID_PARAM_FOUND:
                AppLog.i("Login NO_DEVICEID_PARAM_FOUND!");
                break;
            case NO_DEVICEID_FOUND:
                AppLog.i("Login NO_DEVICEID_FOUND!");
                downloadData();
                break;
            case SAME_DEVICEID_FOUND:
                AppLog.i("Login SAME_DEVICEID_FOUND!");
                if (dbManager.hasUser(App.userName)) {
                    loginDownloadMsg.setAllDataReady();
                    EventBus.getDefault().post(loginDownloadMsg);
                } else {
                    downloadData();
                }
                break;
            case DIFF_DEVICEID_FOUND:
                downloadData();
                break;
        }
    }

    private void downloadData() {
        downloadUserPreferences();
        downloadCollectedArticles();
        downloadHealthAndAvatar();
        downloadCompleteTaskIDs();

        //download其他数据，如温度记录，收藏，LH试纸等
        getRecordDatas();
        downloadAlgorithmData();
        getRecordLHAndHCGAndBUDatas(); // 获取服务器所有试纸信息
        getAllTask();
    }

    private void downloadUserPreferences() {

        dbManager.insertUserPreference(App.userName, App.userPswd);
        dbManager.updateUserPreference(App.userName, "openID", openID);

        OKHttpUtil okHttpClient = new OKHttpUtil(this);

        String appendUrl = "hardware/obtainMacID.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("hardwareType", 1);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        String resultStr = response.body().string();
                        AppLog.i("obtainMacID:" + resultStr);
                        JSONObject respJSONObj = new JSONObject(resultStr);

                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("obtainMacID onResponse success!");
                            downloadMacIDData2DB(respJSONObj);
                            loginDownloadMsg.downloadUserPreferenceOK = true;
                            EventBus.getDefault().post(loginDownloadMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            downloadUserPreferences();
                        } else {
                            loginDownloadMsg.downloadUserPreferenceOK = true;
                            EventBus.getDefault().post(loginDownloadMsg);
                            AppLog.i("obtainMacID onResponse failed! respCode is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("obtainMacID onResponse failed!");
                        e.printStackTrace();
                        loginDownloadMsg.downloadUserPreferenceOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    }
                    AppLog.i("obtainMacID now!");
                }

            });
        } catch (JSONException e) {
            AppLog.i("obtainMacID JSONException!");
            e.printStackTrace();
            loginDownloadMsg.downloadUserPreferenceOK = true;
            EventBus.getDefault().post(loginDownloadMsg);
        }

    }

    private void downloadMacIDData2DB(JSONObject respJSONObj) {
        AppLog.i("start downloadMacIDData2DB!");
        try {
            JSONArray allMACAddressJSONArray = respJSONObj.getJSONArray("MACAddresss");

            if (null != allMACAddressJSONArray && allMACAddressJSONArray.length() != 0) {

                String macAddress = allMACAddressJSONArray.getString(allMACAddressJSONArray.length() - 1);
                dbManager.updateUserPreference(App.userName, "macAddress", macAddress);
                App.memory_preference_macAddress = macAddress;
            }

        } catch (JSONException e) {
            AppLog.i("downloadMacIDData2DB JSONException!");
            e.printStackTrace();
        } catch (Exception e) {
            AppLog.i("downloadMacIDData2DB failed!");
            e.printStackTrace();
        }
    }

    private void downloadCollectedArticles() {
        OKHttpUtil okHttpUtil = new OKHttpUtil(this);
        String appendUrl = "collection/getAllCollections.json?authToken=" + App.authToken;
        okHttpUtil.getAsync(appendUrl, okHttpUtil.new BaseCallBack() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {

                try {
                    JSONObject respJSONObj = new JSONObject(response.body().string());
                    int respCode = respJSONObj.getInt("code");

                    if (200 == respCode) {
                        downloadCollectionData2DB(respJSONObj);
                        downloadCollectionImage2Cache(respJSONObj);
                        loginDownloadMsg.downloadCollectedArticlesOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);

                        AppLog.i("downloadCollectedArticles success! response = " + respJSONObj);
                    } else {
                        AppLog.i("downloadCollectedArticles failed! respCode is:" + respCode);
                    }
                } catch (JSONException e) {
                    AppLog.i("downloadCollectedArticles JSONException!");
                    e.printStackTrace();
                } catch (Exception e) {
                    AppLog.i("downloadCollectedArticles failed!");
                    e.printStackTrace();
                }
            }

            private void downloadCollectionData2DB(JSONObject respJSONObj) {
                AppLog.i("start downloadCollectionData2DB!");

                try {
                    JSONArray allCollectedArticleJSONArray = respJSONObj.getJSONArray("collections");
                    List<CollectedArticle> collectedArticleList = new ArrayList<CollectedArticle>();

                    for (int i = 0; i < allCollectedArticleJSONArray.length(); i++) {
                        JSONObject collectedArticleJSONObj = allCollectedArticleJSONArray.getJSONObject(i);
                        CollectedArticle collectedArticle = new CollectedArticle();
                        collectedArticle.collectionID = collectedArticleJSONObj.getString("collectionID");
                        collectedArticle.collectionName = collectedArticleJSONObj.getString("collectionName");
                        collectedArticle.collectionURL = collectedArticleJSONObj.getString("collectionURL");
                        collectedArticle.collectionFrom = collectedArticleJSONObj.getInt("collectionFrom");
                        collectedArticle.collectionDate = collectedArticleJSONObj.getString("collectionDate");
                        if (!collectedArticleJSONObj.isNull("collectionDelete")) {
                            collectedArticle.collectionDelete = collectedArticleJSONObj.getInt("collectionDelete");
                        } else {
                            collectedArticle.collectionDelete = 0;
                        }
                        collectedArticleList.add(collectedArticle);
                        App.collectedArticleIdList.add(collectedArticle.collectionURL);
                        App.articleId2CollectionIDMap.put(collectedArticle.collectionURL, collectedArticle.collectionID);
                    }

                    dbManager.add(collectedArticleList);
                } catch (JSONException e) {
                    AppLog.i("downloadCollection2DB JSONException!");
                    e.printStackTrace();
                } catch (Exception e) {
                    AppLog.i("downloadCollection2DB failed!");
                    e.printStackTrace();
                }
            }

            private void downloadCollectionImage2Cache(JSONObject respJSONObj) {
                AppLog.i("start downloadCollectionImage2Cache!");

                try {
                    JSONArray allCollectedArticleDetailJSONArray = respJSONObj.getJSONArray("forums");
                    for (int j = 0; j < allCollectedArticleDetailJSONArray.length(); j++) {
                        JSONObject collectedArticleDetailJSONObj = allCollectedArticleDetailJSONArray.getJSONObject(j);
                        // download 所有收藏的文章图片到本地cache
                        String imgUrl = App.articleImageBaseUrlPath + collectedArticleDetailJSONObj.getString("imgName");
                        int articleId = collectedArticleDetailJSONObj.getInt("forumID");
                        String fileName = "collectedArticle" + articleId + ".jpg";
                        SDCardHelper.saveImage2SDCardPrivateCacheDirFromNetwork(imgUrl, fileName, MyDeviceChooseActivity.this);
                    }
                } catch (JSONException e) {
                    AppLog.i("downloadCollectionImage2Cache JSONException!");
                    e.printStackTrace();
                } catch (Exception e) {
                    AppLog.i("downloadCollectionImage2Cache failed!");
                    e.printStackTrace();
                }
            }

        });
    }

    private void downloadHealthAndAvatar() {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "user/getUserInfo.json?authToken=" + App.authToken;
        okHttpClient.getAsync(appendUrl, okHttpClient.new BaseCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String responseStr = response.body().string();
                    AppLog.i("userInfo:" + responseStr);
                    JSONObject respJSONObj = new JSONObject(responseStr);
                    int respCode = respJSONObj.getInt("code");
//                    String headPhoto = respJSONObj.getString("headPhoto");
                    if (App.HTTP_RESP_OK == respCode) {
                        if (respJSONObj.toString().indexOf("headPhoto") != -1) {
                            String avatarName = App.userName + "_avatar.jpg";
                            String picURL = App.avatarUrlPath + App.userName + "/" + respJSONObj.getString("headPhoto");
                            SDCardHelper.saveImage2SDCardPrivateCacheDirFromNetwork(picURL, avatarName, MyDeviceChooseActivity.this);
                        } else {
                        }
                        int mensesLen = respJSONObj.getInt("mensesLen");
                        int periodLen = respJSONObj.getInt("periodLen");
                        int mensesType = respJSONObj.getInt("mensesType");

                        String taskIDs = null;
                        if (respJSONObj.toString().indexOf("taskIDs") != -1) {
                            taskIDs = respJSONObj.getString("taskIDs");
                            if (null != taskIDs && !"".equals(taskIDs)) {
                                dbManager.updateUserPreference(App.userName, "taskIDs", taskIDs, "isTaskIDSynced", 1);
                            }
                        } else {
                            dbManager.updateUserPreference(App.userName, "taskIDs", "1,2,3", "isTaskIDSynced", 0);
                        }

                        String birthday = null;
                        if (respJSONObj.toString().indexOf("birthday") != -1) {
                            birthday = respJSONObj.getString("birthday").split(" ")[0];
                        } else {
                            birthday = "2000-1-1";
                        }

                        String nickName = null;
                        if (respJSONObj.toString().indexOf("nickName") != -1) {
                            nickName = respJSONObj.getString("nickName");
                        }
                        App.saveUserPreference("bindType", "bindThermometer");
                        saveHealthInfo2SQL(mensesLen, periodLen, mensesType, 1);
                        if (null != birthday && !"".equals(birthday)) {
                            dbManager.updateUserPreference(App.userName, "birthday", birthday);
                            App.memory_preference_birthday = birthday;
                        }
                        if (null != nickName && !"".equals(nickName)) {
                            dbManager.updateUserPreference(App.userName, "nickName", nickName, "isNickNameSynced", 1);
                            App.memory_preference_nickName = nickName;
                        }
                        AppLog.i("nickName in LoginActivity after downloaded, App.memory_preference_nickName = " + App.memory_preference_nickName);

                        if (respJSONObj.toString().indexOf("status") != -1) {
                            int status = respJSONObj.getInt("status");
                            dbManager.updateUserPreference(App.userName, "state", String.valueOf(status), "isStateSynced", 1);
                            App.memory_preference_userState = status;
                            AppLog.i("App.memory_preference_userState = " + App.memory_preference_userState);
                        }
                        loginDownloadMsg.downloadHeadPhotoOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    } else {
                        AppLog.i("download health and avatar failed! is:" + respCode);
                        loginDownloadMsg.downloadHeadPhotoOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    loginDownloadMsg.downloadHeadPhotoOK = true;
                    EventBus.getDefault().post(loginDownloadMsg);
                } catch (Exception e) {
                    e.printStackTrace();
                    loginDownloadMsg.downloadHeadPhotoOK = true;
                    EventBus.getDefault().post(loginDownloadMsg);
                }
            }

        });
    }

    private void downloadAlgorithmData() {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "cycle/getAllCycle.json?authToken=" + App.authToken;
        okHttpClient.getAsync(appendUrl, okHttpClient.new BaseCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String responseStr = response.body().string();
                    AppLog.i("downloadAlgorithmData:" + responseStr);
                    JSONObject respJSONObj = new JSONObject(responseStr);
                    int respCode = respJSONObj.getInt("code");
                    if (555 == respCode) {
                        AppLog.i("一代用户初次登录 start");
                        isOldUsersUpdated = true;
                        return;
                    }
                    if (App.HTTP_RESP_OK == respCode) {

                        JSONArray jsonArrayCycleData = respJSONObj.getJSONArray("cycleData");
                        JSONArray jsonArrayDayUserData = respJSONObj.getJSONArray("userData");
                        JSONObject jsonObjectUserInfo = respJSONObj.getJSONObject("userInfo");

                        if (jsonArrayCycleData.length() == 0 || jsonArrayDayUserData.length() == 0 || jsonObjectUserInfo.length() == 0) {
                            AppLog.i("网络无算法数据!");
                            List<DayUnitDSOutput> dayUnitDSOutputList = dbManager.getALDayUnitDSOutputList(App.userName, 0, System.currentTimeMillis() / 1000);
                            // 即网络无算法数据，本地也无算法数据，则认为是一代迁移至二代用户
                            if (dayUnitDSOutputList.size() == 0) {
                                AppLog.i("本地没有算法数据，一代用户初次登录, 初次计算算法数据!");
                                isOldUsersUpdated = true;
                                return;
                            }
                        }

                        if (null != jsonArrayCycleData) {
                            AppLog.i("cycleData:" + jsonArrayCycleData.toString());
                            saveJsonArrayCycleData2DB(jsonArrayCycleData);
                        }

                        if (null != jsonArrayDayUserData) {
                            AppLog.i("userData:" + jsonArrayDayUserData.toString());
                            saveJsonArrayDayUserData2DB(jsonArrayDayUserData);
                        }

                        if (null != jsonObjectUserInfo) {
                            AppLog.i("userInfo:" + jsonObjectUserInfo.toString());
                            savejsonObjectUserInfo2DB(jsonObjectUserInfo);
                        }
                        loginDownloadMsg.downloadAlgorithmDataOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    } else {
                        AppLog.i("downloadAlgorithmData failed! is:" + respCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });

    }

    private void saveHealthInfo2SQL(int mensesLen, int periodLen, int mensesType, int isSynced) {

        ArrayList<String> columnNames = new ArrayList<String>();
        columnNames.add("mensesLen");
        columnNames.add("periodLen");
        columnNames.add("mensesType");

        ArrayList<String> columnValues = new ArrayList<String>();
        columnValues.add(String.valueOf(mensesLen));
        columnValues.add(String.valueOf(periodLen));
        columnValues.add(String.valueOf(mensesType));

        dbManager.updateUserPrefList(App.userName, columnNames, columnValues, "isHealthInfoSynced", isSynced);

        App.memory_preference_mensesLen = mensesLen;
        App.memory_preference_periodLen = periodLen;
        App.memory_preference_mensesType = mensesType;
    }

    private void savejsonObjectUserInfo2DB(JSONObject jsonObjectUserInfo) {

        UserUnitDS userUnitDS = new UserUnitDS();

        try {
            userUnitDS.validCycleCount = Integer.valueOf(jsonObjectUserInfo.getString("validCycleCount"));
            userUnitDS.averageMenstruationLength = Float.valueOf(jsonObjectUserInfo.getString("averageMenstruationLength"));
            userUnitDS.menstruationLengthError = Float.valueOf(jsonObjectUserInfo.getString("menstruationErrorLength"));
            userUnitDS.averageCycleLength = Float.valueOf(jsonObjectUserInfo.getString("averageCycleLength"));
            userUnitDS.cycleLengthError = Float.valueOf(jsonObjectUserInfo.getString("cycleErrorLength"));
            userUnitDS.averageLuteumPhaseLength = Float.valueOf(jsonObjectUserInfo.getString("averageLuteumPhaseLength"));
            userUnitDS.abnormalCaseAlert = Integer.valueOf(jsonObjectUserInfo.getString("abnormalCaseAlert"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        dbManager.saveALUserData(userUnitDS, 1);
    }

    private void saveJsonArrayDayUserData2DB(JSONArray jsonArrayDayUserData) {

        List<DayUnitDSOutput> dayOutput = new ArrayList<>();
        JSONObject jsonObject;
        DayUnitDSOutput dayUnitDSOutput;
        for (int i = 0; i < jsonArrayDayUserData.length(); i++) {
            try {

                jsonObject = jsonArrayDayUserData.getJSONObject(i);
                dayUnitDSOutput = new DayUnitDSOutput();
                dayUnitDSOutput.date = DateUtil.getStringToDate(jsonObject.getString("infoDate"));
                //AppLog.i("date: "+ DateUtil.getDateTimeStr(dayUnitDSOutput.date));
                dayUnitDSOutput.periodAchieveForecast = Integer.valueOf(jsonObject.getString("periodAchieveForecast"));
                dayUnitDSOutput.periodAchieveConfirm = Integer.valueOf(jsonObject.getString("periodAchieveConfirm"));
                dayUnitDSOutput.periodAvoidForecast = Integer.valueOf(jsonObject.getString("periodAvoidForecast"));
                dayUnitDSOutput.periodAvoidConfirm = Integer.valueOf(jsonObject.getString("periodAvoidConfirm"));
                dayUnitDSOutput.homePageMenstruationEnd = Integer.valueOf(jsonObject.getString("homePageMenstruationEnd"));
                dayUnitDSOutput.homePageOvulation = Integer.valueOf(jsonObject.getString("homePageOvulation"));
                dayUnitDSOutput.homePageConceptionChance = Float.valueOf(jsonObject.getString("homePageConceptionChance"));
                dayUnitDSOutput.homePageNextMenstruation = Integer.valueOf(jsonObject.getString("homePageNextMenstruation"));
                dayUnitDSOutput.dayOfCycle = Integer.valueOf(jsonObject.getString("dayOfCycle"));

                dayOutput.add(dayUnitDSOutput);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        dbManager.saveALDayOutput(dayOutput, 1);
    }

    /**
     * 从服务器获取任务数据
     */
    private void downloadCompleteTaskIDs() {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "task/getComplete.json?authToken=" + App.authToken;
        okHttpClient.getAsync(appendUrl, okHttpClient.new BaseCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String responseStr = response.body().string();
                    JSONObject respJSONObj = new JSONObject(responseStr);
                    int respCode = respJSONObj.getInt("code");
                    if (App.HTTP_RESP_OK == respCode) {
                        JSONArray comTasksJSONArray = respJSONObj.getJSONArray("comTasks");
                        saveCompleteTaskIDs2SQL(comTasksJSONArray);
                        AppLog.i("download complete task ids failed! is:" + comTasksJSONArray);
                        loginDownloadMsg.downloadCompleteTaskIDsOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    } else {
                        AppLog.i("download complete task ids failed! is:" + respCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }

    /**
     * 通过map来将日期和完成的任务一一对应，并将其保存至本地数据库
     * <p/>
     * key 时间，value 已完成的任务（字符串）
     * <p/>
     * map为空或map中没有重复key的时候，将数据添加到map中；
     * 当map中已有重复的key的时候，将原有key所对应的value取出与新taskID拼接，最终把新value保存至map中
     *
     * @param comTasksJSONArray
     * @throws JSONException
     */
    private void saveCompleteTaskIDs2SQL(JSONArray comTasksJSONArray) throws JSONException {

        dbManager.insertUserCompleteTaskIDs(comTasksJSONArray, 1);

    }

    private void saveJsonArrayCycleData2DB(JSONArray jsonArrayCycleData) {

        CycleUnitDS[] cycleOutput = new CycleUnitDS[jsonArrayCycleData.length()];
        JSONObject jsonObject;
        CycleUnitDS cycleUnitDS;
        for (int i = 0; i < jsonArrayCycleData.length(); i++) {
            try {

                jsonObject = jsonArrayCycleData.getJSONObject(i);
                cycleUnitDS = new CycleUnitDS();
                cycleUnitDS.cycleNumber = Integer.valueOf(jsonObject.getString("cycleNumber"));
                cycleUnitDS.menstruationStartForecast = Long.valueOf(jsonObject.getString("menstruationStartForecast"));
                cycleUnitDS.menstruationEndForecast = Long.valueOf(jsonObject.getString("menstruationEndForecast"));
                cycleUnitDS.menstruationStartConfirm = Long.valueOf(jsonObject.getString("menstruationStartConfirm"));
                cycleUnitDS.menstruationEndConfirm = Long.valueOf(jsonObject.getString("menstruationEndConfirm"));
                cycleUnitDS.peakDay = Long.valueOf(jsonObject.getString("peakDay"));
                cycleUnitDS.ovulationDayForecast = Long.valueOf(jsonObject.getString("ovulationDayForecast"));
                cycleUnitDS.ovulationDayConfirm = Long.valueOf(jsonObject.getString("ovulationDayConfirm"));
                cycleUnitDS.ovulationDayUserRecord = Long.valueOf(jsonObject.getString("ovulationDayUserRecord"));
                cycleUnitDS.ovulationDayUserRecordBasis = Integer.valueOf(jsonObject.getString("ovulationDayUserRecordBasis"));
                cycleUnitDS.ovulationDayBBTRise = Long.valueOf(jsonObject.getString("ovulationDayBBTRiseDay"));
                cycleUnitDS.ovulationDayNextMenstruation = Long.valueOf(jsonObject.getString("ovulationDayNextMenstruation"));
                cycleUnitDS.fertileWindowStartForecast = Long.valueOf(jsonObject.getString("fertileStartForecast"));
                cycleUnitDS.fertileWindowEndForecast = Long.valueOf(jsonObject.getString("fertileEndForecast"));
                cycleUnitDS.fertileWindowStartConfirm = Long.valueOf(jsonObject.getString("fertileStartConfirm"));
                cycleUnitDS.fertileWindowEndConfirm = Long.valueOf(jsonObject.getString("fertileEndConfirm"));
                cycleUnitDS.dangerWindowStartForecast = Long.valueOf(jsonObject.getString("dangerStartForecast"));
                cycleUnitDS.dangerWindowEndForecast = Long.valueOf(jsonObject.getString("dangerEndForecast"));
                cycleUnitDS.dangerWindowStartConfirm = Long.valueOf(jsonObject.getString("dangerStartConfirm"));
                cycleUnitDS.dangerWindowEndConfirm = Long.valueOf(jsonObject.getString("dangerEndConfirm"));
                cycleUnitDS.nextMenstruationStartForecast = Long.valueOf(jsonObject.getString("nextMenstruationStartForecast"));
                cycleUnitDS.nextMenstruationEndForecast = Long.valueOf(jsonObject.getString("nextMenstruationEndForecast"));
                cycleUnitDS.nextOvulationDayForecast = Long.valueOf(jsonObject.getString("nextOvulateForecast"));
                cycleUnitDS.nextFertileWindowStartForecast = Long.valueOf(jsonObject.getString("nextFertileStartForecast"));
                cycleUnitDS.nextFertileWindowEndForecast = Long.valueOf(jsonObject.getString("nextFertileEndForecast"));
                cycleUnitDS.nextDangerWindowStartForecast = Long.valueOf(jsonObject.getString("nextDangerStartForecast"));
                if (jsonObject.has("nextDangerEndForecast"))
                    cycleUnitDS.nextDangerWindowEndForecast = Long.valueOf(jsonObject.getString("nextDangerEndForecast"));
                else cycleUnitDS.nextDangerWindowEndForecast = 0;
                cycleOutput[i] = cycleUnitDS;

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        dbManager.saveALCycleOutput(cycleOutput, 1);
    }

    private void getRecordDatas() {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "sync/getAllSignsRecords.json?authToken=" + App.authToken;
        okHttpClient.getAsync(appendUrl, okHttpClient.new BaseCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String responseStr = response.body().string();
                    AppLog.i("userRecordInfo:" + responseStr);
                    JSONObject respJSONObj = new JSONObject(responseStr);
                    int respCode = respJSONObj.getInt("code");
                    if (App.HTTP_RESP_OK == respCode) {
                        JSONArray jsonArrayRecordData = respJSONObj.getJSONArray("records");
                        //读取records中的温度并保存
                        saveTemperatureData(jsonArrayRecordData);
                        saveRecordInfoData(jsonArrayRecordData);
                        AppLog.i("getAllSignsRecords failed! is:" + jsonArrayRecordData);
                        loginDownloadMsg.downloadRecordInfoOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    } else {
                        AppLog.i("getAllSignsRecords failed! is:" + respCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }

    private void saveTemperatureData(JSONArray jsonArrayRecordData) {
        JSONArray jsonArray;
        JSONObject jsonObject;
        JSONObject jsonObjectTemper;
        UserTemperatureInfo userTemperatureInfo;
        for (int i = 0; i < jsonArrayRecordData.length(); i++) {
            try {
                jsonObject = jsonArrayRecordData.getJSONObject(i);
                jsonArray = jsonObject.getJSONArray("temperatures");
                for (int j = 0; j < jsonArray.length(); j++) {
                    jsonObjectTemper = jsonArray.getJSONObject(j);
                    AppLog.i(jsonObjectTemper.toString());
                    userTemperatureInfo = new UserTemperatureInfo();
                    userTemperatureInfo.setTemperatureId(jsonObjectTemper.getString("temperatureID"));
                    userTemperatureInfo.setTemperature(jsonObjectTemper.getDouble("basalBodyTempreture"));
                    if (userTemperatureInfo.getTemperature() < 35) continue;
                    userTemperatureInfo.setMeasureTime(DateUtil.getStringToDate(jsonObjectTemper.getString("temperatureDate")));
                    userTemperatureInfo.setSyncType(1);
                    userTemperatureInfo.setUserName(App.userName);
                    userTemperatureInfo.setIsBBT(jsonObjectTemper.getInt("isBBT"));
                    if (!jsonObjectTemper.isNull("deleted")) {
                        userTemperatureInfo.setIsDelete(jsonObjectTemper.getInt("deleted"));
                    } else {
                        userTemperatureInfo.setIsDelete(0);
                    }
                    dbManager.saveTempearatureData(userTemperatureInfo);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void saveRecordInfoData(JSONArray jsonArrayRecordData) {
        JSONObject jsonObject;
        UserRecordData userRecordData;
        for (int i = 0; i < jsonArrayRecordData.length(); i++) {
            try {
                jsonObject = jsonArrayRecordData.getJSONObject(i);
                userRecordData = new UserRecordData();
                userRecordData.setId(jsonObject.getString("id"));
                userRecordData.setUserName(App.userName);
                userRecordData.setRecordDate(DateUtil.getStringToDate(jsonObject.getString("recordDate")));
                userRecordData.setMucusInfo(jsonObject.getInt("mucilage"));
                userRecordData.setMensesInfo(jsonObject.getInt("menstruationProperty"));
                userRecordData.setCopulationInfo(jsonObject.getInt("hadSex"));
                userRecordData.setSymptomInfo(jsonObject.getInt("tag"));
                if (jsonObject.has("memo"))
                    userRecordData.setMemoInfo(jsonObject.getString("memo"));
                if (jsonObject.has("sexTime"))
                    userRecordData.setSexTime(DateUtil.getStringToDate(jsonObject.getString("sexTime")));
                if (jsonObject.has("recordEditDate"))
                    userRecordData.setRecordEditDate(DateUtil.getStringToDate(jsonObject.getString("recordEditDate")));
                userRecordData.setOvulationInfo(jsonObject.getInt("ovulatoryTest"));
                userRecordData.setIsSynced(1);
                dbManager.saveRecordData(userRecordData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        userRecordData = dbManager.getLastMensesRecordData(App.userName);
        if (null != userRecordData) {
            dbManager.updateUserPreference(App.userName, "lastPeriodDate", DateUtil.getDateStr2bit(userRecordData.getRecordDate()));
            App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(userRecordData.getRecordDate());
        }
    }

    /**
     * 获取服务器所有试纸信息
     */
    private void getRecordLHAndHCGAndBUDatas() {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "gyna/getAllSignsGynas.json?authToken=" + App.authToken;
        okHttpClient.getAsync(appendUrl, okHttpClient.new BaseCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String responseStr = response.body().string();
                    JSONObject respJSONObj = new JSONObject(responseStr);
                    int respCode = respJSONObj.getInt("code");
                    if (App.HTTP_RESP_OK == respCode) {
                        JSONArray LHsJsonArray = respJSONObj.getJSONArray("LHs");
                        JSONArray HCGsJsonArray = respJSONObj.getJSONArray("HCGs");
                        JSONArray BUsJsonArray = respJSONObj.getJSONArray("BUs");
                        saveLHs2SQL(LHsJsonArray);
                        saveHCGs2SQL(HCGsJsonArray);
                        saveBUs2SQL(BUsJsonArray);

                        loginDownloadMsg.downloadRecordLHAndHCGAndBUDatasOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    } else {
                        AppLog.i("getRecordLHAndHCGAndBUDatas failed! is:" + respCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 将LH试纸保存至本地数据库
     *
     * @param LHsJSONArray
     * @throws JSONException
     */
    private void saveLHs2SQL(JSONArray LHsJSONArray) throws Exception {
        for (int i = 0; i < LHsJSONArray.length(); i++) {
            JSONObject LHsJSONObj = new JSONObject(LHsJSONArray.get(i).toString());
            if (!LHsJSONObj.isNull("LHdelete")) {
                dbManager.insertRecordLH(App.userName, LHsJSONObj.getString("LHDate"), LHsJSONObj.getString("LHPaperID"), LHsJSONObj.getInt("LHResult"), LHsJSONObj.getInt("LHdelete"), 1);
            } else {
                dbManager.insertRecordLH(App.userName, LHsJSONObj.getString("LHDate"), LHsJSONObj.getString("LHPaperID"), LHsJSONObj.getInt("LHResult"), 0, 1);
            }
        }
    }

    /**
     * 将HCG试纸保存至本地数据库
     *
     * @param HCGsJSONArray
     * @throws JSONException
     */
    private void saveHCGs2SQL(JSONArray HCGsJSONArray) throws Exception {
        for (int i = 0; i < HCGsJSONArray.length(); i++) {
            JSONObject HCGsJSONObj = new JSONObject(HCGsJSONArray.get(i).toString());
            if (!HCGsJSONObj.isNull("HCGdelete")) {
                dbManager.insertRecordHCG(App.userName, HCGsJSONObj.getString("HCGDate"), HCGsJSONObj.getString("HCGPaperID"), HCGsJSONObj.getInt("HCGResult"), HCGsJSONObj.getInt("HCGdelete"), 1);
            } else {
                dbManager.insertRecordHCG(App.userName, HCGsJSONObj.getString("HCGDate"), HCGsJSONObj.getString("HCGPaperID"), HCGsJSONObj.getInt("HCGResult"), 0, 1);
            }

        }
    }

    /**
     * 将BU试纸保存至本地数据库
     *
     * @param BUsJSONArray
     * @throws JSONException
     */
    private void saveBUs2SQL(JSONArray BUsJSONArray) throws Exception {
        for (int i = 0; i < BUsJSONArray.length(); i++) {
            JSONObject BUsJSONObj = new JSONObject(BUsJSONArray.get(i).toString());
            if (!BUsJSONObj.isNull("BUdelete")) {
                dbManager.insertRecordBU(App.userName, BUsJSONObj.getString("BUDate"), BUsJSONObj.getString("BUltraID"), BUsJSONObj.getInt("BUdelete"), 1);
            } else {
                dbManager.insertRecordBU(App.userName, BUsJSONObj.getString("BUDate"), BUsJSONObj.getString("BUltraID"), 0, 1);
            }
        }
    }

    private void getAllTask() {

        OKHttpUtil okHttpUtil = new OKHttpUtil(this);
        String appendUrl = "task/getAllTask.json";
        try {
            okHttpUtil.add("authToken", App.authToken);
            okHttpUtil.add("language", "ch");
            okHttpUtil.postAsync(appendUrl, okHttpUtil.new BaseCallBack() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            super.onFailure(request, e);
                        }

                        @Override
                        public void onResponse(Response response) throws IOException {
                            String respStr = response.body().string();

                            try {
                                JSONObject respJSONObj = new JSONObject(respStr);
                                int respCode = respJSONObj.getInt("code");

                                if (App.HTTP_RESP_OK == respCode) {
                                    GetAllTask getAllTask = JSON.parseObject(respStr, GetAllTask.class);
                                    if (getAllTask != null) {

                                        dbManager.initTaskDetail(1, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(0).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(0).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "基础体温", "BBT",
                                                "48c3fc", "3DB4F9", 2, 6, 8, 11, getAllTask.getSysTask().get(1).getDate(), "测量基础体温", "Measure BBT ");

                                        dbManager.initTaskDetail(2, App.userName, 1, 1, "", "", "", "",
                                                "", "1178E7", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "饮水6-8杯", "6-8 glasses of water");

                                        dbManager.initTaskDetail(3, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(2).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                getAllTask.getSysTask().get(2).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "叶酸", "Folic Acid",
                                                "8F40DE", "8F40DE", 2, 4, 5, 15, getAllTask.getSysTask().get(2).getDate(), "服用叶酸", "Take Folic Acid");

                                        dbManager.initTaskDetail(4, App.userName, 1, 1, "", "", "", "",
                                                "", "9A7EE3", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "健身运动", "Working out");

                                        dbManager.initTaskDetail(5, App.userName, 1, 1, "", "",
                                                "", "", "", "41CF74", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "吃水果", "Daily Fruits");

                                        dbManager.initTaskDetail(6, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(5).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(5).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "宫颈粘液", "Cervical Mucus",
                                                "cf7edd", "C363D5", 2, 6, 6, 20, getAllTask.getSysTask().get(1).getDate(), "观察宫颈粘液", "Check Cervical Mucus");
                                        dbManager.initTaskDetail(7, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(6).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(6).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "排卵试纸", "Test",
                                                "85CC54", "F9575C", 2, 6, 10, 14, getAllTask.getSysTask().get(1).getDate(), "测试排卵试纸", "Ovulation Test");
                                        dbManager.initTaskDetail(8, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(7).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(7).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "B超", "Ultrasound",
                                                "F6BE3A", "FDB50A", 0, 2, 0, 10, getAllTask.getSysTask().get(1).getDate(), "B超检查", "Ultrasound Examination");
                                    } else {
//
                                    }
                                    loginDownloadMsg.downloadSysTaskOK = true;
                                    EventBus.getDefault().post(loginDownloadMsg);
                                } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                                    OKHttpUtil.setNewToken();
                                    getAllTask();
                                } else {
                                    AppLog.i("error code! code = " + respCode);
                                }
                            } catch (JSONException e) {
                                AppLog.i("JSONException e");
                                e.printStackTrace();
                            }
                        }
                    }

            );
        } catch (
                JSONException e
                )

        {
            e.printStackTrace();
        }

    }

    @Subcriber
    private void handleLoginDownloadMsgInMyDeviceChoose(final LoginDownloadMsgInMyDeviceChoose loginDownloadMsg) {
        if (loginDownloadMsg.isDataDownloadedOK()) {
            if (needInitMemory) {
                doInitMemory();
            }
        }

        if (loginDownloadMsg.downloadHeadPhotoOK && loginDownloadMsg.downloadRecordInfoOK && isOldUsersUpdated) {
            isOldUsersUpdated = false;
            initALgorithmData();
        }

        if (loginDownloadMsg.isAllDataReady() && !needInitMemory) {
            if (progressDialog != null && progressDialog.isShowing())
                progressDialog.setMessage(getString(R.string.loginOK));

            setDataDownloaded();

            dbManager.updateUserPreference(App.userName, "openID", openID);
            App.saveUserPreference(App.SHARED_PREF_USER_NAME, App.userName);
            App.saveUserPreference(App.SHARED_PREF_USER_TOKEN, App.authToken);
            Intent intent = new Intent(MyDeviceChooseActivity.this, MainActivity.class);
            intent.putExtra("isNeedFirstExecAL", isNeedFirstExecAL);
            dismissProgressDialog();
            startActivity(intent);
            //finish();
        }
    }

    private void doInitMemory() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                initCollectionIDsIntoMemory();
                initUserPreferencesIntoMemory();
                initDayUnitDSOutputsListIntoMemory();

                needInitMemory = false;
                EventBus.getDefault().post(loginDownloadMsg);
            }
        }).start();
    }

    private void initALgorithmData() {

        UserUnitDS userData = new UserUnitDS();
        int mensesLen = App.memory_preference_mensesLen;
        if (mensesLen == 0) {
            mensesLen = 5;
            dbManager.updateUserPreference(App.userName, "mensesLen", "5");
            App.memory_preference_mensesLen = 5;
        }
        int periodLen = App.memory_preference_periodLen;
        if (periodLen == 0) {
            periodLen = 28;
            dbManager.updateUserPreference(App.userName, "periodLen", "28");
            App.memory_preference_periodLen = 28;
        }

        if (null != App.memory_preference_lastPeriodDate && !"".equals(App.memory_preference_lastPeriodDate)) {
            long lastPeriodDate = DateUtil.getStringToDate(App.memory_preference_lastPeriodDate + " 00:00:00");
            if ((lastPeriodDate + 2 * App.memory_preference_periodLen * 24 * 3600) < System.currentTimeMillis() / 1000) {
                loginDownloadMsg.downloadAlgorithmDataOK = true;
                EventBus.getDefault().post(loginDownloadMsg);
                isNeedFirstExecAL = 1;
                return;
            }
        } else {
            loginDownloadMsg.downloadAlgorithmDataOK = true;
            EventBus.getDefault().post(loginDownloadMsg);
            isNeedFirstExecAL = 1;
            return;
        }

        userData.averageMenstruationLength = mensesLen;
        userData.averageCycleLength = periodLen;
        DayUnitDSInput[] dayInput = dbManager.getDayInputListFromG1Record(App.userName);

        userData.showLog();
        for (int i = 0; i < dayInput.length; i++)
            dayInput[i].showLog();
        if (dayInput.length == 0) {
            loginDownloadMsg.downloadAlgorithmDataOK = true;
            EventBus.getDefault().post(loginDownloadMsg);
            isNeedFirstExecAL = 1;
            return;
        }
        //long firstPS = DateUtil.getDateZeroTime2bit(DateUtil.getStringToDate(App.memory_preference_lastPeriodDate + " 12:00:00"));
        //AppLog.i("Algorithm firstPS = " + firstPS);

        algorithm.g1FirstLoginG2(userData, dayInput, 0);

        JSONArray jsonArrayCycleDatas = algorithm.getCycleOutputJson();
        JSONArray jsonArrayUserDatas = algorithm.getDayOutputJson();
        JSONObject jsonObjectUserData = algorithm.getUserInfoJson();
        UploadCycleData(jsonArrayCycleDatas, jsonArrayUserDatas, jsonObjectUserData);
    }

    private void setDataDownloaded() {
        dbManager.updateUserPreference(App.userName, "isDataDownloaded", "true");
    }

    private void initCollectionIDsIntoMemory() {
        dbManager.initCollectionIDs2Memory(App.userName);
    }

    private void initUserPreferencesIntoMemory() {
        dbManager.initUserPreferences2Memory(App.userName);
    }

    private void initDayUnitDSOutputsListIntoMemory() {
        dbManager.initDayUnitDSOutputsList2Memory(App.userName);
    }

    private void UploadCycleData(final JSONArray jsonArrayCycleDatas, final JSONArray jsonArrayUserDatas, final JSONObject jsonObjectUserData) {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas.toString());
            AppLog.i("userData = " + jsonArrayUserDatas.toString());
            AppLog.i("userInfo = " + jsonObjectUserData.toString());
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("cycleData", jsonArrayCycleDatas);
            okHttpClient.add("userData", jsonArrayUserDatas);
            okHttpClient.add("userInfo", jsonObjectUserData);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    saveALResult2Sqlite(0);
                    loginDownloadMsg.downloadAlgorithmDataOK = true;
                    EventBus.getDefault().post(loginDownloadMsg);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            saveALResult2Sqlite(1);
                            loginDownloadMsg.downloadAlgorithmDataOK = true;
                            EventBus.getDefault().post(loginDownloadMsg);
                            AppLog.i("UploadCycleData onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            UploadCycleData(jsonArrayCycleDatas, jsonArrayUserDatas, jsonObjectUserData);
                        } else {
                            saveALResult2Sqlite(0);
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                            loginDownloadMsg.downloadAlgorithmDataOK = true;
                            EventBus.getDefault().post(loginDownloadMsg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        loginDownloadMsg.downloadAlgorithmDataOK = true;
                        EventBus.getDefault().post(loginDownloadMsg);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();
            loginDownloadMsg.downloadAlgorithmDataOK = true;
            EventBus.getDefault().post(loginDownloadMsg);
        }

    }

    private void saveALResult2Sqlite(int isSynced) {
        algorithm.saveALData2Sqlite(isSynced);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
        openID = null;
        registerSimpleType = 0;
    }
}
